<!--检测方案的关联检测项操作组件-->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="600px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form 
      ref="formRef" 
      :model="localFormData" 
      :rules="rules" 
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检测项编码" prop="index_code">
            <el-input 
              v-model="localFormData.index_code" 
              placeholder="请选择检测项"
              readonly
              @click.native="showTestItemDialog"
            >
              <el-button 
                slot="append" 
                icon="el-icon-search"
                @click="showTestItemDialog"
                :disabled="listLoading"
              ></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检测项名称" prop="index_name">
            <el-input 
              v-model="localFormData.index_name" 
              placeholder="请输入检测项名称"
              @blur="checkNameUnique"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检测项类型" prop="index_type">
            <el-select
              v-model="localFormData.index_type"
              placeholder="请选择检测项类型"
              style="width: 100%"
            >
              <el-option 
                v-for="item in indexTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检测工具" prop="qc_tool">
            <el-input 
              v-model="localFormData.qc_tool" 
              placeholder="请输入检测工具"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="检测要求" prop="check_method">
        <el-input
          v-model="localFormData.check_method"
          type="textarea"
          :rows="2"
          placeholder="请输入检测要求"
        ></el-input>
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="标准值" prop="stander_val">
            <el-input-number 
              v-model="localFormData.stander_val" 
              placeholder="请输入标准值"
              :precision="4"
              :step="0.0001"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input 
              v-model="localFormData.unit" 
              placeholder="请输入单位"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="10">  
        <el-col :span="12">
            <el-form-item label="误差下限" prop="threshold_min" style="margin-right: -10px;">
            <el-input-number 
                v-model="localFormData.threshold_min" 
                placeholder="下限"
                :min="0"
                :precision="4"
                :step="0.0001"
                style="width: 100%"
            ></el-input-number>
            </el-form-item>
        </el-col>
        
        <el-col :span="12">
            <el-form-item label="误差上限" prop="threshold_max" style="margin-left: -10px;">
            <el-input-number 
                :min="0"
                v-model="localFormData.threshold_max" 
                placeholder="上限"
                :precision="4"
                :step="0.0001"
                style="width: 100%"
            ></el-input-number>
            </el-form-item>
        </el-col>
      </el-row>
      
      
      
      <el-form-item label="备注">
        <el-input
          v-model="localFormData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>
    </el-form>
    
    <!-- 检测项选择对话框 -->
    <el-dialog
      title="选择检测项"
      :visible.sync="testItemSelectDialogVisible"
      width="70%"
      append-to-body
    >
      <div class="filter-container">
        <el-input
          v-model="listQuery.index_name"
          placeholder="搜索检测项名称"
          style="width: 200px;"
          clearable
          @keyup.enter.native="handleFilter"
          :disabled="listLoading"
        />
        
        <div class="search-item">
          <span class="search-label">检测项类型</span>
          <el-select
            v-model="listQuery.index_type"
            placeholder="全部类型"
            clearable
            style="width: 180px;"
            @change="handleFilter"
            :disabled="listLoading"
          >
            <el-option
              v-for="item in itemTypes"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        
        <el-button 
          type="primary" 
          @click="handleFilter" 
          :loading="listLoading"
        >搜索</el-button>
      </div>
      
      <el-table
        :data="testItemList"
        border
        style="width: 100%"
        v-loading="listLoading"
        @row-click="handleTestItemSelect"
      >
        <el-table-column
          prop="index_code"
          label="检测项编码"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="index_name"
          label="检测项名称"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="index_type"
          label="检测项类型"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="qc_tool"
          label="检测工具"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :disabled="listLoading"
        />
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button 
          @click="testItemSelectDialogVisible = false" 
          :disabled="listLoading"
        >取 消</el-button>
      </span>
    </el-dialog>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" :disabled="submitting">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { checkTemplateNameUnique, saveOrUpdateTemplateIndex, getTestItemList } from '@/api/qc/QualitySchemeOrder';
import _ from 'lodash';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({
        record_id: null,
        template_id: null,
        index_id: null,
        index_code: '',
        index_name: '',
        index_type: '',
        qc_tool: '',
        check_method: '',
        stander_val: null,
        unit: '',
        threshold_max: null,
        threshold_min: null,
        doc_url: '',
        remark: ''
      })
    },
    isEditMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 本地表单数据，避免直接修改 prop
      localFormData: JSON.parse(JSON.stringify(this.formData)),
      
      // 检测项选择相关数据
      testItemSelectDialogVisible: false,
      testItemList: [],
      listLoading: false,
      isFetching: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        index_name: '',
        index_type: ''
      },
      itemTypes: [
        '尺寸',
        '物理性能检测',
        '外观',
        '化学成分检测',
        '环境与耐久性测试',
        '工艺性能测试',
        '无损检测',
        '力学性能检测',
        '金相检测',
        '特殊用途检测'
      ],
      
      submitting: false,
      indexTypeOptions: [
        { label: '数值型', value: '1' },
        { label: '文本型', value: '2' },
        { label: '布尔型', value: '3' }
      ],
      rules: {
        index_code: [
          { required: true, message: '请输入检测项编码', trigger: 'blur' }
        ],
        index_name: [
          { required: true, message: '请输入检测项名称', trigger: 'blur' },
          { validator: this.validateNameUnique, trigger: 'blur' }
        ],
        index_type: [
          { required: true, message: '请选择检测项类型', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    formData: {
      deep: true,
      handler(newVal) {
        this.localFormData = JSON.parse(JSON.stringify(newVal))
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEditMode ? '修改检测项' : '添加检测项'
    },
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    async showTestItemDialog() {
      this.testItemSelectDialogVisible = true;
      await this.getTestItems();
    },
    
    async getTestItems() {
      if (this.isFetching) return;
      
      this.listLoading = true;
      this.isFetching = true;
      
      try {
        const response = await getTestItemList({
          pageNum: this.listQuery.page,
          pageSize: this.listQuery.limit,
          index_name: this.listQuery.index_name,
          index_type: this.listQuery.index_type
        });
        
        this.testItemList = response.records || [];
        this.total = response.total || 0;
      } catch (error) {
        console.error('获取检测项列表失败:', error);
        this.$message.error('获取检测项列表失败');
      } finally {
        this.listLoading = false;
        this.isFetching = false;
      }
    },
    
    handleTestItemSelect(row) {
      if (this.submitting) return;
      
      this.localFormData = {
        ...this.localFormData,
        index_id: row.index_id,
        index_code: row.index_code,
        index_name: row.index_name,
        index_type: row.index_type,
        qc_tool: row.qc_tool,
        remark: row.remark,
        check_method: row.check_method,
        stander_val: row.stander_val,
        unit: row.unit,
        threshold_max: row.threshold_max,
        threshold_min: row.threshold_min,
        doc_url: row.doc_url
      };
      this.testItemSelectDialogVisible = false;
    },
    
    handleFilter: _.debounce(function() {
      this.listQuery.page = 1;
      this.getTestItems();
    }, 500),
    
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getTestItems();
    },
    
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getTestItems();
    },
    
    async checkNameUnique() {
      if (!this.localFormData.index_name) return;
      try {
        const res = await checkTemplateNameUnique(this.localFormData.index_name);
        if (!res) {
          this.$message.warning('该检测项名称已存在，请修改');
        }
      } catch (error) {
        console.error('验证名称唯一性失败:', error);
      }
    },
    
    validateNameUnique(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入检测项名称'));
        return;
      }
      
      checkTemplateNameUnique(value).then(res => {
        if (res) {
          callback();
        } else {
          callback(new Error('该检测项名称已存在'));
        }
      }).catch(() => {
        callback();
      });
    },
    
    handleClose() {
      this.$refs.formRef.resetFields();
      this.$emit('close');
    },
    
    async handleSubmit() {
      try {
        const valid = await this.$refs.formRef.validate();
        if (!valid) return;

        if (!this.localFormData.template_id) {
          this.$message.error('缺少关联的方案ID');
          return;
        }
        
        this.submitting = true;
        
        const response = await saveOrUpdateTemplateIndex(this.localFormData);
        
        if (response) {
          this.$message.success(this.isEditMode ? '修改成功' : '添加成功');
          this.$emit('submit', { ...this.localFormData });
          this.dialogVisible = false;
        } else {
          this.$message.error('操作失败，请重试');
        }
      } catch (error) {
        console.error('提交失败:', error);
        this.$message.error('提交失败，请检查网络或联系管理员');
      } finally {
        this.submitting = false;
      }
    }
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 18px;
}

.el-row {
  margin-bottom: 10px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 10px;
  padding-bottom: 10px;
  flex-wrap: wrap;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-label {
  white-space: nowrap;
  font-size: 14px;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>